import { defineStore } from 'pinia'
import { LoginApi } from '@/api/user'
import { GetInformationApi } from '@/api/common'

// 创建名为 'user' 的 store
export const useUserStore = defineStore('user', {
    state: () => {
        let token = localStorage.getItem("token")
        let info_data = localStorage.getItem("info_data")
        return {
            // 是否登录
            login: token ? true : false,
            // token
            token: token ?? "",
            // 菜单
            menus: [],
            // 基本信息
            info_data: info_data ? JSON.parse(info_data) : null,
            mode: "default",
            id: null
        }
    },
    actions: {
        /**
         * 登录
         * @param {*} data 
         * @param {string} mode - 登录模式，默认为 'default'，也可以是 'tec'
         * @returns {object} - 登录结果
         */
        async handleLogin(data = {}, mode = 'default') {
            let loginRes;
            try {
                if (mode == 'default') {
                    loginRes = await LoginApi(data);
                }
                if (loginRes.success) {
                    this.mode = mode;
                    this.token = loginRes.entity.token;
                    this.login = true;
                    this.id = loginRes.entity.userId;
                    localStorage.setItem('token', this.token)
                    let infoRes = await this.handleGetInformation();
                    if (!infoRes.success) {
                        return {
                            success: false,
                            message: "用户信息获取失败"
                        }
                    }

                }
            } catch (error) {

                return {
                    success: false,
                    message: "登录失败"
                }
            }
            return loginRes;

        },
        /**
        * 获取用户信息
        * @returns {object} - 获取信息结果
        */
        async handleGetInformation() {
            let infoRes = { success: false };
            if (this.mode == 'default') {
                infoRes = await GetInformationApi();
            }
            if (infoRes.success) {
                // infoRes.entity.auditStatus = 1;
                this.info_data = infoRes.entity;
                localStorage.setItem('info_data', JSON.stringify(infoRes.entity))
            }
            return infoRes
        },
        /**
         * 退出登录
         */
        handleExit() {
            localStorage.clear();
            this.login = false;
            this.token = "";
            this.menus = [];
            this.info_data = null;
        }
    }
})